package com.example.product.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.product.entity.Account;
import com.example.product.entity.Admin;
import com.example.product.exception.CustomException;
import com.example.product.mapper.AdminMapper;
import com.example.product.service.AdminService;
import com.example.product.util.Result;
import com.example.product.util.TokenUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import lombok.extern.log4j.Log4j2;

import java.util.*;
import java.util.function.Function;

/**
 * 管理员业务处理
 **/
@Service
@Transactional
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements AdminService {

    @Autowired
    private TokenUtil tokenUtil;

    @Autowired
    private AdminMapper adminMapper;

    /**
     * 登录
     */
    public Result login(Account account) {
        try{
            // 对密码进行加密
            System.out.println("开始处理登录请求");
            String encryptedPassword = SecureUtil.md5(account.getPassword());
            System.out.println("加密密码: " + encryptedPassword);
            // 创建查询条件
            QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("username", account.getUsername());
            System.out.println("尝试登录用户: " + account.getUsername());
            System.out.println("密码: " + account.getPassword());
            System.out.println("加密密码: " + encryptedPassword);

            // 查找用户
            Admin admin = adminMapper.selectOne(queryWrapper);
            // 检查用户是否存在
            if (admin == null) {
                return new Result(401, "用户名或密码错误，用户不存在", null); // 用户不存在
            }
            // 检查密码是否正确
            if (!admin.getPassword().equals(encryptedPassword)) {
                System.out.println("加密密码: " + encryptedPassword);
                return new Result(401, "用户名或密码错误，密码不匹配", null); // 密码不匹配
            }

            // 生成 token
            Account adminAccount = convertAdminToAccount(admin);
            String token = tokenUtil.createToken(adminAccount); // 使用注入的 TokenUtil
            Map<String, Object> responseData = new HashMap<>();
            responseData.put("token", token);
            responseData.put("role", admin.getRole());
            responseData.put("name", admin.getName());
            responseData.put("img", admin.getImg());
            responseData.put("username", admin.getUsername());
            responseData.put("password",admin.getPassword());
            responseData.put("id",admin.getId());
            System.out.println("响应数据: " + responseData);
            // 登录成功，返回 token
            return new Result(200, "登录成功", responseData);
        }catch (Exception e) {
            e.printStackTrace(); // 打印异常堆栈信息
            return new Result(500, "服务器内部错误", null);
        }
    }



    private Account convertAdminToAccount(Admin admin) {
        Account account = new Account();
        account.setId(admin.getId());
        account.setUsername(admin.getUsername());
        account.setName(admin.getName());
        account.setRole(admin.getRole());
        account.setImg(admin.getImg());
        return account;
    }

    @Override
    /**
     * 新增
     */
    public void add(Admin admin) {
        Admin dbAdmin = adminMapper.selectByUsername(admin.getUsername());
        if (ObjectUtil.isNotNull(dbAdmin)) {
            throw new CustomException("用户已存在");
        }
        if (ObjectUtil.isEmpty(admin.getPassword())) {
            admin.setPassword("admin");
        }
        if (ObjectUtil.isEmpty(admin.getName())) {
            admin.setName(admin.getUsername());
        }
        admin.setRole("ADMIN");
        adminMapper.insert(admin);
    }

    /**
     * 删除
     */
    @Override
    public void deleteById(Integer id) {
        adminMapper.deleteById(id);
    }

    @Override
    public boolean saveBatch(Collection<Admin> entityList, int batchSize) {
        return false;
    }

    @Override
    public boolean saveOrUpdateBatch(Collection<Admin> entityList, int batchSize) {
        return false;
    }

    /**
     * 修改
     */
    @Override
    public boolean updateById(Admin admin) {
        adminMapper.updateById(admin);
        return false;
    }

    @Override
    public boolean updateBatchById(Collection<Admin> entityList, int batchSize) {
        return false;
    }

    @Override
    public boolean saveOrUpdate(Admin entity) {
        return false;
    }

    @Override
    public Admin getOne(Wrapper<Admin> queryWrapper, boolean throwEx) {
        return null;
    }

    @Override
    public Optional<Admin> getOneOpt(Wrapper<Admin> queryWrapper, boolean throwEx) {
        return Optional.empty();
    }

    @Override
    public Map<String, Object> getMap(Wrapper<Admin> queryWrapper) {
        return null;
    }

    @Override
    public <V> V getObj(Wrapper<Admin> queryWrapper, Function<? super Object, V> mapper) {
        return null;
    }

    @Override
    public AdminMapper getBaseMapper() {
        return null;
    }

    @Override
    public Class<Admin> getEntityClass() {
        return null;
    }

    /**
     * 根据ID查询
     */
    @Override
    public Admin selectById(Integer id) {
        return adminMapper.selectById(id);
    }

    /**
     * 查询所有
     */
    @Override
    public List<Admin> selectAll(Admin admin) {
        return adminMapper.selectAll(admin);
    }

    /**
     * 分页查询
     */
    @Override
    public PageInfo<Admin> selectPage(Admin admin, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Admin> list = adminMapper.selectAll(admin);
        return new PageInfo<>(list);
    }


    /**
     * 修改密码
     */
    public void updatePassword(Account account) {
        Admin dbAdmin = adminMapper.selectByUsername(account.getUsername());
        if (ObjectUtil.isNull(dbAdmin)) {
            throw new CustomException("用户不存在");
        }
        if (!account.getPassword().equals(dbAdmin.getPassword())) {
            throw new CustomException("原密码错误");
        }
        dbAdmin.setPassword(account.getNewPassword());
        adminMapper.updateById(dbAdmin);
    }
}